﻿using System;
using System.Net;
using System.Net.Mail;

namespace BalloonShop.App_Code
{
    /// <summary>
    /// 包含杂项功能的类
    /// </summary>
    public class Utilities
    {
        static Utilities()
        {
            //
            //TODO:在此添加构造函数
            //
        }

        //用于发送电子邮件的通用方法
        public static void SendMail(string from, string to, string subject, string body)
        {
            //配置邮件客户端
            SmtpClient mailClient = new SmtpClient(BalloonShopConfiguration.MailServer);

            //设置验证信息（针对需要身份验证的SMTP服务器）
            mailClient.Credentials = new NetworkCredential(BalloonShopConfiguration.MailUsername, BalloonShopConfiguration.MailPassword);
            //创建电子邮件
            MailMessage mailMessage = new MailMessage(from, to, subject, body);
            //发送电子邮件
            mailClient.Send(mailMessage);
        }

        //发送错误日志邮件
        public static void LogError(Exception ex) {
            //获取当前日期和时间
            string dateTime = DateTime.Now.ToLongDateString() + ".at" + DateTime.Now.ToShortTimeString();
            //存储错误消息
            string errorMessage = "Exception generated on " + dateTime;
            //获取产生错误的页面
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            errorMessage += "\n\n Page location:" + context.Request.RawUrl;
            //构建错误消息
            errorMessage += "\n\n Message: " + ex.Message;
            errorMessage += "\n\n Source: " + ex.Source;
            errorMessage += "\n\n TargetSite: " + ex.TargetSite;
            errorMessage += "\n\n StackTrace: " + ex.StackTrace;
            //如果web.config中激活了改选项就发送错误邮件
            if (BalloonShopConfiguration.EnableErrorLogEmail)
            {
                string from = BalloonShopConfiguration.MailFrom;
                string to = BalloonShopConfiguration.ErrorLogEmail;
                string subject = "BalloonShop Error Report";
                string body = errorMessage;
                SendMail(from, to, subject, body);
            }
        }
    }
}